package org.esti.model.dao.impl;

import org.esti.model.KnowledgeField;
import org.esti.model.dao.KnowledgeFieldDAO;
import org.esti.model.exceptions.KnowledgeFieldDoesNotExistException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @author Artem Loginov (logart)
 */
@Repository
public class KnowledgeFieldDAOimpl implements KnowledgeFieldDAO {

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * {@inheritDoc}
     */
    @Transactional(readOnly = true)
    @Override
    public List<KnowledgeField> getAllKnowledgeFields() {

        Query query = entityManager.createQuery("SELECT kf FROM KnowledgeField kf");
        return query.getResultList();

    }

    /**
     * {@inheritDoc}
     */
    @Transactional(readOnly = true)
    @Override
    public KnowledgeField getKnowledgeFieldById(long id) {
        try {
            return entityManager.find(KnowledgeField.class, id);
        } catch (NoResultException ex) {
            throw new KnowledgeFieldDoesNotExistException(ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Transactional
    @Override
    public KnowledgeField add(KnowledgeField knowledgeField) {
        return entityManager.merge(knowledgeField);
    }

    /**
     * {@inheritDoc}
     */
    @Transactional
    @Override
    public void remove(long id) {
        KnowledgeField knowledgeFieldx = entityManager.find(KnowledgeField.class, id);
        entityManager.remove(knowledgeFieldx);
    }
}
